package com.czn.encryptable_demo.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author Zenan Chen
 * @date 2023/1/10 16:42
 */
@RestController
@RequestMapping("/test")
public class TestController extends BasicController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Resource(name = "jasyptStringEncryptor")
    private StringEncryptor stringEncryptor;

    @RequestMapping(value = "encryptPw", method = RequestMethod.POST)
    @ApiOperation(value = "使用jasypt加密", notes = "返回密文")
    public @ResponseBody Object encryptPw(@ApiParam(value = "密码明文", required = true) @RequestParam String password) {
        try {
            String encrypted = stringEncryptor.encrypt(password);
            return this.outBound("ENC(" + encrypted + ")");
        } catch (Exception e) {
            log.error("------------->/test/encryptPw 加密异常: ", e);
            return this.errorHandler("jasypt加密失败: " + e.getMessage());
        }
    }

    @RequestMapping(value = "decryptPw", method = RequestMethod.POST)
    @ApiOperation(value = "使用jasypt解密", notes = "返回明文")
    public @ResponseBody Object decryptPw(@ApiParam(value = "密码密文", required = true) @RequestParam String password) {
        try {
            if (!password.startsWith("ENC(") || !password.endsWith(")")) {
                return this.errorHandler("密文须以'ENC('开头且以')'结尾");
            }
            return this.outBound(stringEncryptor.decrypt(password.substring(4, password.length() - 1)));
        } catch (Exception e) {
            log.error("------------->/test/decryptPw 加密异常: ", e);
            return this.errorHandler("jasypt解密密失败: " + e.getMessage());
        }
    }
}
